package com.xbongbong.saas.model.impl;/*/*/

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.saas.domain.dao.WorkOrderFormDao;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateCategoryEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderTemplateEntityExt;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderTemplateCategoryModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 * @date 2019/3/14 11:09
 * @since v1.0
 * @version v1.0
 */
@Service("workOrderFromModel")
public class WorkOrderFormModelImpl implements WorkOrderFormModel {
    @Resource
    private WorkOrderFormDao workOrderFormDao;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private WorkOrderTemplateCategoryModel workOrderTemplateCategoryModel;

    @Override
    public Integer insert(WorkOrderFormEntity entity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        return workOrderFormDao.insert(entity);
    }

    @Override
    public Integer update(WorkOrderFormEntity entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());
        return workOrderFormDao.update(entity);
    }

    @Override
    public List<WorkOrderFormEntity> findEntitys(Map<String, Object> param) {
        return workOrderFormDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return workOrderFormDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public Integer deleteByKey(Long key, String corpid) {
        return workOrderFormDao.deleteByKey(key, corpid);
    }

    @Override
    public WorkOrderFormEntityExt getByKey(Long key, String corpid) {
        return workOrderFormDao.getByKey(key, corpid);
    }

    @Override
    public WorkOrderFormEntityExt getByKeyIncludeDel(Long key, String corpid) {
        return workOrderFormDao.getByKeyIncludeDel(key, corpid);
    }

    @Override
    public WorkOrderFormEntityExt getByTemplateId(Long templateId, String corpid) {
        return workOrderFormDao.getByTemplateId(templateId, corpid);
    }

    @Override
    public List<WorkOrderFormEntityExt> findEntitysExt(Map<String, Object> param) {
        return workOrderFormDao.findEntitysExt(param);
    }

    @Override
    public List<WorkOrderFormEntity> initBatch(List<WorkOrderFormEntity> list, String corpid) {
        workOrderFormDao.initBatch(list, corpid);
        return list;
    }

    @Override
    public WorkOrderFormEntityExt getDefaultAllListForm() {
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", "0");
        param.put("del", 0);
        List<WorkOrderFormEntityExt> entitys = findEntitysExt(param);
        return entitys.get(0);
    }

    @Override
    public List<WorkOrderFormEntityExt> getByIdIn(Collection<Long> idIn, String corpid) {
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("idIn", idIn);
        param.put("del", 0);
        return findEntitysExt(param);
    }

    @Override
    public List<WorkOrderFormEntity> updateBatch(List<WorkOrderFormEntity> list, String corpid) {
        workOrderFormDao.updateBatch(list, corpid);
        return list;
    }
    /**
     * 批量插入实体
     * @param list
     * @return 返回数据的列表
     */
    @Override
    public List<WorkOrderFormEntity> insertBatch(List<WorkOrderFormEntity> list) {
        workOrderFormDao.insertBatch(list);
        return list;
    }
    /**
     * 批量删除
     * @param list 主键id集合
     * @param corpid
     * @author xingxing.xiao
     */
    @Override
    public Integer deleteBatch(List<Long> list, String corpid) {
        return workOrderFormDao.deleteBatch(list, corpid);
    }

    @Override
    public List<WorkOrderFormEntity> getTemplateWithPermission(String corpid, UserVO loginUser, Long appId, Integer isFree) {
        String userId = loginUser.getUserId();
        boolean isBoss = loginUser.isAdminOrBoss();
        boolean maxDataPermission = loginUser.isMaxDataPermission();

        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("enable",1);
        if (appId != null && appId != -1) {
            param.put("appId", appId);
        }
        if (isFree != null) {
            param.put("isFree", isFree);
        }
        List<WorkOrderTemplateEntityExt> workOrderTemplateEntityExts = workOrderTemplateModel.findEntitys(param);
        List<Long> templateIds = new ArrayList<>();
        //fix ： 19575 【工单设置】变更分类排序后，列表页对应模板的排序规则建议跟着分类来
        param.clear();
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("orderByStr","sort desc");
        param.put("appId", appId);
        List<WorkOrderTemplateCategoryEntity> workOrderTemplateCategoryEntityList = workOrderTemplateCategoryModel.findEntitys(param);
        List<WorkOrderTemplateEntity> newWorkOrderTemplateEntityExts = new LinkedList<>();
        for (WorkOrderTemplateCategoryEntity entity : workOrderTemplateCategoryEntityList) {
            List<WorkOrderTemplateEntity> newList = getWorkOrderTemplateEntityExtsBy(entity.getId(), workOrderTemplateEntityExts);
            newWorkOrderTemplateEntityExts.addAll(newList);
        }
        for (WorkOrderTemplateEntity entityExt : newWorkOrderTemplateEntityExts) {
            //如果是超管,老板,以及全公司数据权限的都能看,产品凤娇说的   @date 2019/5/24 15:31
            // 38397 【成功部】全公司的工单权限，其中一个工单模板没有给该人员授权，但是她在全部分组下还是能看到该工单模板下的数据
            if (isBoss) {
                templateIds.add(entityExt.getId());
                continue;
            }

            String scopeRule = entityExt.getScopeRule();
            JSONObject scopeRuleObj =  JSONObject.parseObject(scopeRule);
            String deptStr = scopeRuleObj.getString("dept");
            List<Long> deptList = JSONArray.parseArray(deptStr, Long.class);
            String userStr = scopeRuleObj.getString("user");
            List<String> userList = JSONArray.parseArray(userStr, String.class);
            if ((deptList == null || deptList.size() == 0) && (userList == null || userList.size() == 0)) {
                // 如果没填值就默认全公司
                templateIds.add(entityExt.getId());
                continue;
            }
            List<String> depUserIdList = new ArrayList<>();
            if (deptList != null && deptList.size() > 0) {
                // 获取子部门的depId
                deptList = departmentModel.getSubDepIdList(corpid, deptList);
                depUserIdList = userModel.getDepUserIdList(corpid, deptList);
            }
            userList.addAll(depUserIdList);
            if (userList.contains(userId)) {
                templateIds.add(entityExt.getId());
            }

        }
        param.clear();
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("templateIdIn", templateIds);
        List<WorkOrderFormEntity> workOrderFormEntityList = findEntitys(param);
        List<WorkOrderFormEntity> newworkOrderFormList = new LinkedList<>();
        for (Long templateId : templateIds) {
            List<WorkOrderFormEntity> newList = getWorkOrderFormListByTemplateId(workOrderFormEntityList, templateId);
            newworkOrderFormList.addAll(newList);
        }
        return newworkOrderFormList;
    }

    private List<WorkOrderTemplateEntity> getWorkOrderTemplateEntityExtsBy(Long categoryId, List<WorkOrderTemplateEntityExt> entityList) {
        List<WorkOrderTemplateEntity> newList = new LinkedList<>();
        for (WorkOrderTemplateEntity entityExt : entityList) {
            if (Objects.equals(categoryId, entityExt.getCategoryId())) {
                newList.add(entityExt);
            }
        }
        return newList;
    }


    private List<WorkOrderFormEntity> getWorkOrderFormListByTemplateId(List<WorkOrderFormEntity> workOrderFormEntityList, Long templateId) {
        List<WorkOrderFormEntity> newList = new LinkedList<>();
        for (WorkOrderFormEntity entity : workOrderFormEntityList) {
            if (Objects.equals(templateId, entity.getTemplateId())) {
                newList.add(entity);
            }
        }
        return newList;
    }
}
